package com.lancoo.answer.widget.audioPlayView;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.text.Html;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

import com.google.gson.Gson;
import com.lancoo.answer.R;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.util.DensityUtils;
import com.lancoo.answer.util.DpUtils;
import com.lancoo.answer.util.NetWorkTools;
import com.lancoo.answer.util.TimerUtil;
import com.lancoo.answer.widget.VoiceWaveView;
import com.lancoo.answer.widget.subject.ISelectSubjectListener;
import com.lancoo.answer.widget.subject.SubjectSelectAdapter;
import com.lancoo.answer.widget.subject.SubjectSelectHelper;
import com.rxjava.rxlife.RxLife;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


public class TopicAudioView extends RelativeLayout implements View.OnClickListener , IAudioCallback , LifecycleObserver {
    private boolean isPlaying = false;
    private SeekBar seekBar;
    private ImageView iv_play,iv_load;
    private TextView tv_title,tv_time;
    private Config config;
    private int duration;
    private AudioPlayCallBack callBack;
    private boolean isTouching;
    private boolean isRelease = true;
    private TextView tv_count;
    private static final String TAG  = "TopicAudioView";
    private View tv_enable;
    private VoiceWaveView waveView;
    private int currentIndex = 0;
    private AnimationDrawable drawables;
    private long currentCount;
    private RelativeLayout rl_border,rl_state;
    private TextView tv_speed;
    private int currentPosition = 2;


    public void setConfig(Config config) {
        this.config = config;
        if (config!=null){
            if (tv_title!=null && !TextUtils.isEmpty(config.soundName)){
                tv_title.setText(Html.fromHtml(config.soundName));
                tv_title.setVisibility(VISIBLE);
            }else {
                tv_title.setVisibility(INVISIBLE);
            }

            if (!config.isAutoMode){
                rl_border.setBackgroundResource(R.drawable.ev_shape_oval_sound_play_bg);
                rl_state.setBackgroundResource(R.drawable.ev_shape_oval_sound_play);
                iv_play.setImageResource(R.mipmap.ev_ic_sound_play);
                tv_count.setVisibility(GONE);
                tv_enable.setVisibility(GONE);
            }else {

                if (config.isEnable){
                    rl_border.setBackgroundResource(R.drawable.ev_shape_oval_sound_play_bg);
                    rl_state.setBackgroundResource(R.drawable.ev_shape_oval_sound_play);
                    iv_play.setImageResource(R.drawable.ev_bg_null);
                    tv_count.setText("3");
                    tv_count.setVisibility(VISIBLE);
                    tv_count.bringToFront();
                }else {  //不可点击状态
                    rl_border.setBackgroundResource(R.drawable.ev_shape_oval_sound_play_bg_unable);
                    rl_state.setBackgroundResource(R.drawable.ev_shape_oval_sound_play_unable);
                    iv_play.setImageResource(R.mipmap.ev_ic_sound_play);
                    tv_count.setVisibility(GONE);


                    tv_enable.setVisibility(GONE);
                    tv_enable.bringToFront();
                }
            }
            seekBar.setEnabled(config.isEnable);
            iv_play.setEnabled(config.isEnable);
            TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
            int paperType = taskControlBean.getPaperType();
            if (config.isTestMode||paperType==3){
                iv_play.setVisibility(VISIBLE);
                iv_play.setEnabled(config.isEnable);  //考试分为：考试模式和查看模式，是否可以交互由外部决定
                iv_play.setImageResource(R.mipmap.ev_ic_media_play_1);
                tv_count.setVisibility(GONE);
                tv_enable.setVisibility(GONE);
                if(paperType==3){
                    waveView.randomWave();
                }
            }

            if (config.isSpeedEnable){
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) waveView.getLayoutParams();
                layoutParams.rightMargin = DensityUtils.dp2px(getContext(),35);
                waveView.requestLayout();
            }else {
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) waveView.getLayoutParams();
                layoutParams.rightMargin = DensityUtils.dp2px(getContext(),10);
                waveView.requestLayout();
            }

            tv_speed.setVisibility(config.isSpeedEnable?VISIBLE:GONE);

            tv_speed.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
//播放速度弹出层
                    List<Float> data = new ArrayList<>();
                    if (config.speedRates!=null && config.speedRates.size()>0){
                        data.addAll(config.speedRates);
                    }else {
                        data.add(0.8f);
                        data.add(0.9f);
                        data.add(1.0f);
                        data.add(1.1f);
                        data.add(1.2f);
                    }

                    new SubjectSelectHelper.Builder(getContext())
                            .isShowTop(false)
                            .title("筛选")
                            .cancle("取消")
                            .confirm("确定")
                            .adapter(data, new SubjectSelectAdapter<Float>(currentPosition) {
                                @Override
                                public void convert(@NonNull TextView selectItem, Float item) {
                                    selectItem.setText(item.toString()+"X");
                                    selectItem.setTextSize(16f);
                                }
                            })
                            .listener(new ISelectSubjectListener<Float>() {
                                @Override
                                public void onConfirm(int position) {
                                    currentPosition = position;
                                    if (config.mediaEngine!=null){
                                        config.mediaEngine.speed(data.get(position));
                                    }
                                    tv_speed.setText(data.get(position).toString()+"X");
                                }
                            })
                            .show();

                }
            });
        }
    }



    public void startTimeCountAndPlay(boolean isAutoMode){
        if (!isAutoMode || !config.isEnable){
            return;
        }
        config.isAutoMode = isAutoMode;
        if (waveView!=null){
            waveView.stop();
        }

        TimerUtil.startCount(4, new TimerUtil.IcountTimer() {
            @Override
            public void onCountdown(Long l) {

                if (!config.isAutoMode){
                    iv_play.setImageResource(R.mipmap.ev_ic_sound_play);
                    tv_count.setVisibility(GONE);
                }else {
                    tv_count.setText((l-1)+"");
                    iv_play.setImageResource(R.drawable.ev_bg_null);
                    tv_count.setVisibility(l==1?GONE:VISIBLE);
                    tv_count.bringToFront();
                }

                if (l == 1){
//                    isRelease = true;
                    play();
                    iv_play.setEnabled(true);
                    seekBar.setEnabled(true);
                }else {
                    iv_play.setEnabled(false);
                    seekBar.setEnabled(false);
                }
                if (l>1){
                    playTipSound();
                }
                if (l==1){
                    iv_play.setVisibility(VISIBLE);
                    iv_play.setImageResource(R.mipmap.ev_ic_sound_pause);
                }


                tv_enable.setVisibility(GONE);
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void playTipSound() {
        SoundPool.Builder builder = new SoundPool.Builder();
        builder.setMaxStreams(5);
        AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
        attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
        builder.setAudioAttributes(attrBuilder.build());//加载一个AudioAttributes
        SoundPool soundPool = builder.build();

        AssetManager assetManager = getContext().getAssets();
        try {
            AssetFileDescriptor afd = assetManager.openFd("pet_train_countdown.mp3");
            int id = soundPool.load(afd,1);
            soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                @Override
                public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                    soundPool.play(id,1,1,1,0,1);
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void pauseTimeer(){
        if (config==null || !config.isAutoMode){
            return;
        }
        TimerUtil.pauseCount();
//        reset();
        pause();
//        if (waveView!=null){
//            waveView.stop();
//        }
//        playOrPauseVoiceView();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate(){
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy(){
        if (config.isTestMode){
            isPlaying = false;
            currentIndex = 0;
            release();   //释放掉一些资源
            stopPlayTestingAnimation();  //当前Ac走了onDestroy时，暂停所有播放动效
//            playOrPauseVoiceView();
            if (waveView!=null){
                waveView.stop();
            }
        }else {
            if (waveView!=null){
                waveView.stop();   //重置为暂停状态
            }
            isPlaying = false;
            currentIndex = 0;
            release();
        }

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause(){

        if (config.isTestMode){
            return;
        }
        if (config.isAutoMode){
            pauseTimeer();
        }else {
            pause();
        }
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume(){
        if (config.isTestMode){
            return;
        }
        if (!ConstantBean.Companion.getTaskControlBean().isTraining()){
            return;
        }
        config.isAutoMode = ConstantBean.Companion.getTaskControlBean().getEnableAutoPlay() ==1;
        config.isEnable = ConstantBean.Companion.getTaskControlBean().getEnableAnwer() ==1;
        changeEnableState(config.isEnable);
        if (config.isAutoMode && config.isEnable){
            startTimeCountAndPlay(config.isAutoMode);
        }
    }


    public static class Config{
        private  MediaEngine mediaEngine;
        private String soundName;
        private String audioUrl;
        private boolean isAutoMode;
        private boolean isTestMode;
        private boolean isEnable;
        private int replayCount = 1;
        private boolean isSpeedEnable;
        private List<String> audioList;
        private List<Float> speedRates;

        public Config(String soundName,String audioUrl,boolean isAutoMode,boolean isTestMode,boolean isEnable,boolean isSpeedEnable,List<Float> speedRates,int replayCount,MediaEngine mediaEngine,List<String> audioList){
            this.soundName = soundName;
            this.audioUrl = audioUrl;
            this.mediaEngine = mediaEngine;
            this.isAutoMode = isAutoMode;
            this.isEnable = isEnable;
            this.replayCount = replayCount;
            this.audioList = audioList;
            this.isTestMode = isTestMode;
            this.isSpeedEnable = isSpeedEnable;
            this.speedRates = speedRates;
            Log.e("666777",""+new Gson().toJson(audioList));
        }
    }


    public void changeEnableState(boolean isEnable){
        config.isEnable = isEnable;
        if (seekBar!=null)seekBar.setEnabled(isEnable);
        if (iv_play!=null)iv_play.setEnabled(isEnable);
        if (rl_border!=null) rl_border.setBackgroundResource(isEnable?R.drawable.ev_shape_oval_sound_play_bg:R.drawable.ev_shape_oval_sound_play_bg_unable);
        if (rl_state!=null) rl_state.setBackgroundResource(isEnable?R.drawable.ev_shape_oval_sound_play:R.drawable.ev_shape_oval_sound_play_unable);
    }

    public TopicAudioView(Context context) {
        super(context);
        init(context);
    }

    public TopicAudioView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public TopicAudioView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {

        LayoutInflater.from(context).inflate(R.layout.ev_sound_play_control_layout,this);
        rl_border = findViewById(R.id.rl_border);
        rl_state = findViewById(R.id.rl_state);
        iv_play = findViewById(R.id.img_playState);
        tv_count = findViewById(R.id.tv_count);
        tv_time  = findViewById(R.id.tv_progress_time);
        tv_title = findViewById(R.id.tv_sound_name);
        iv_load = findViewById(R.id.img_load);
        waveView  = findViewById(R.id.voiceWaveView5);
//        initWaveView();

        int widthInPx = DpUtils.getWidthInPx(context);
        int heightInPx = DpUtils.getHeightInPx(context);
        int width = getWidth();
//        Log.e("112233","width:"+width);
        if(widthInPx>heightInPx){
            ViewGroup.LayoutParams layoutParams = waveView.getLayoutParams();
            layoutParams.width=widthInPx/16*4;
            waveView.setLayoutParams(layoutParams);
        }
        tv_speed = findViewById(R.id.tv_speed);
//        initWaveView();





        iv_load.setVisibility(GONE);
        iv_play.setOnClickListener(this);
        tv_enable = findViewById(R.id.tv_enable);
        tv_enable.setRotation(20);
        seekBar = findViewById(R.id.seekBar);
        seekBar.setProgress(0);
        seekBar.setMax(100);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (isTouching){
                    if (config.mediaEngine!=null){
                        config.mediaEngine.seekTo(progress);
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isTouching = true;
                pause();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isTouching = false;
                play();
            }
        });

    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if(ConstantBean.Companion.getTaskControlBean().getEnableAnwer()==0){
            return;
        }
        if(ConstantBean.Companion.getTaskControlBean().getPaperType()==3){
            return;
        }

        if (iv_load.getVisibility()==VISIBLE){
            return;
        }
        if (id == R.id.img_playState){
            if (isPlaying){
                pause();
            }else {

                if(callBack!=null && !config.isTestMode){
                    callBack.onAudioPlay();
                }
                if(currentIndex>=config.audioList.size()){
                    return;
                }
                if (config.audioList.get(currentIndex).length()<20){
                    if (currentCount==1 || currentCount==0){ //倒计时完毕
                        play();
                    }else {
                        delayPlay(currentCount+"");
                    }

                }else {
                    play();
                }



            }
        }
    }



    public  String getFormatMMSS(long needFromatTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
        String formatTime = formatter.format(needFromatTime);
        return formatTime;
    }

    private void showLoadingAnim(){
        Animation mRotateAnimation = new RotateAnimation(0.0f, 720.0f, Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
        mRotateAnimation.setFillAfter(true);
        mRotateAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
        mRotateAnimation.setDuration(1500);
        mRotateAnimation.setRepeatCount(Animation.INFINITE);
        mRotateAnimation.setRepeatMode(Animation.RESTART);
        iv_load.setAnimation(mRotateAnimation);
        iv_load.setVisibility(VISIBLE);
    }

    private void clearLoadingAnim(){
        iv_load.clearAnimation();
        iv_load.setVisibility(GONE);
    }


    private void loading(){
        showLoadingAnim();
    }


    @Override
    public void play(){
        if (config==null || config.mediaEngine == null){
            return;
        }
        if (!config.isTestMode){
            if (isRelease){
                if (currentIndex==0 && iv_load.getVisibility() != VISIBLE){  //如果第一次加载才显示加载动画
                    loading();
                }
                isRelease = false;
                if (config.audioList!=null && config.audioList.size()>0){
                    config.mediaEngine.setUpMedia(config.audioList.get(currentIndex), this);
                }else {
                    config.mediaEngine.setUpMedia(config.audioUrl, this);
                }
                return;
            }
            config.mediaEngine.start();
            iv_play.setVisibility(VISIBLE);
            iv_play.setImageResource(R.mipmap.ev_ic_sound_pause);
            rl_state.setBackgroundResource(R.drawable.ev_shape_oval_sound_play_bg);
            iv_play.setKeepScreenOn(true);
            isPlaying = true;
            isRelease = false;
            if (waveView!=null){
                waveView.start();
            }
            updatePalyingMode(true);
//            playOrPauseVoiceView();
        }else {

            //由于是考试系统自己控制音频的播放，这里只需将IAudioCallback暴露给调用方即可
            isPlaying = true;
            isRelease = false;
            startPlayTestingAnimation();
//            playOrPauseVoiceView();
            if (waveView!=null && !waveView.isStart()){
                waveView.start();

            }

        }
    }

    //开启喇叭动效
    private void startPlayTestingAnimation(){
        Log.e("aaaa","开启喇叭动效！！");
        drawables = new AnimationDrawable();
        //添加一帧动画
        drawables.addFrame(getResources().getDrawable(R.mipmap.ev_ic_media_play_1),300);
        drawables.addFrame(getResources().getDrawable(R.mipmap.ev_ic_media_play_2),300);
        drawables.addFrame(getResources().getDrawable(R.mipmap.ev_ic_media_play_3),300);
        drawables.setOneShot(false);
        iv_play.setImageDrawable(drawables);
        drawables.start();
    }

    //停止喇叭动效
    public void stopPlayTestingAnimation(){
        Log.e("aaaa","停止喇叭动效！！");
        if (drawables !=null){
            drawables.stop();
        }
        if (iv_play!=null){
            iv_play.setImageResource(R.mipmap.ev_ic_media_play_1);
        }
        if (waveView==null){
            return;
        }
        updatePalyingMode(false);
        waveView.stop();
    }





    @Override
    public void pause(){
        if (config==null || config.mediaEngine == null){
            return;
        }

        if (config.isTestMode){
            return;
        }

        if (iv_load!=null){
            iv_load.clearAnimation();
            iv_load.setVisibility(GONE);
        }

        if (config.isTestMode){   //考试模式
            isPlaying = false;
            stopPlayTestingAnimation();
            if (waveView!=null){
                waveView.stop();
            }
        }else {
            int enableAnwer = ConstantBean.getTaskControlBean().getEnableAnwer();
            if (enableAnwer==1){   //config.mediaEngine.isPlaying()
                config.mediaEngine.pause();
                Log.e("6666777","音频播放暂停了");
                iv_play.setKeepScreenOn(false);
                iv_play.setImageResource(R.mipmap.ev_ic_sound_play);
                isPlaying = false;
                iv_play.setEnabled(true);
                tv_count.setVisibility(GONE);
//                playOrPauseVoiceView();
                if (waveView!=null){
                    waveView.stop();
                    updatePalyingMode(false);
                }
                TimerUtil.pauseCount();
            }
        }
    }


    @Override
    public void reset(){   //onComplete会调用
        if ( config==null || config.mediaEngine == null){
            return;
        }

        config.mediaEngine.pause();   //暂停音频播放
        isRelease = true;
        isPlaying = false;

//        if (waveView!=null){
//            waveView.stop();   //重置为暂停状态
//        }

        if (seekBar!=null){
            seekBar.setProgress(0);
            seekBar.setMax(0);
            seekBar.setSecondaryProgress(0);
        }

        tv_time.setText(getFormatMMSS(0)+"/"+getFormatMMSS(duration));
//        iv_play.setImageResource(R.mipmap.ev_ic_sound_play);
        tv_count.setVisibility(GONE);
        Log.e("6666777","reset 音频播完了");
        if (currentIndex==config.audioList.size()-1){   //全部播放完毕
            currentIndex=0;
            if (waveView!=null){
                waveView.stop();   //重置为暂停状态
            }
            iv_play.setImageResource(R.mipmap.ev_ic_sound_play);
//            playOrPauseVoiceView();
            iv_play.setKeepScreenOn(false);
            updatePalyingMode(false);
        }else {
            currentIndex++;
            if(config.audioList.size()<=currentIndex){
                return;
            }
            if (config.audioList.get(currentIndex).length()<20 ){   //判断是否需要延迟
                delayPlay(config.audioList.get(currentIndex));  //延迟一段时间后再播放
            }else {
                play();
            }
        }

    }

    @Override
    public void onError() {  //如果是音频播放出错，
        isRelease = true;
        Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
                    if(getContext()==null){
                        return;
                    }
                    long currentTimeMillis = System.currentTimeMillis();
                    boolean networkConnected = NetWorkTools.isNetworkConnected(getContext());
                    long currentTimeMillis1 = System.currentTimeMillis();
                    long l = currentTimeMillis1 - currentTimeMillis;
                    emitter.onNext(networkConnected);
                }) .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this))
                .subscribe(result -> {
                    if (result) {
                        play();
                    } else {
                        pause();
                    }
                }, throwable -> {

                });
    }

    @Override
    public void onPrepared() {
        clearLoadingAnim();
    }

    private void updatePalyingMode(boolean isPlaying){
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean.getTrainSence() != 0) return;
        taskControlBean.setQuesAudioPlaying(isPlaying);
    }

    private void delayPlay(String duration){
        if(TextUtils.isEmpty(duration)){
            return;
        }
        isPlaying = true;
        iv_play.setImageResource(R.mipmap.ev_ic_sound_pause);
//        playOrPauseVoiceView();
        if (waveView!=null){
            waveView.start();
        }
        int delay = Integer.parseInt(duration);
        currentCount = delay;
        TimerUtil.startCount(delay, new TimerUtil.IcountTimer() {
            @Override
            public void onCountdown(Long l) {
                currentCount= l;
                if (l == 1){
                    currentIndex++;  //倒计时结束，定位到下一个
                    play();
                }
            }
        });
    }

    @Override
    public void updateProgress(int current,int duration){
        clearLoadingAnim();
        TopicAudioView.this.duration = duration;
        if (seekBar!=null){
            seekBar.setMax(duration);
            seekBar.setProgress(current);
        }
        if (tv_time!=null){
            tv_time.setText(getFormatMMSS(current)+"/"+getFormatMMSS(duration));
        }

    }

    @Override
    public void onLoading(int buffer,int duration) {
        if (seekBar!=null && duration>=buffer && duration>0){
            seekBar.setMax(duration);
            seekBar.setSecondaryProgress(buffer);
        }
    }


    public void release(){
        if (config!=null &&  config.mediaEngine!=null)
            config.mediaEngine.release();
    }

    public void setCallBack(AudioPlayCallBack callBack){
        this.callBack=callBack;
    }

}
